import datetime

from flask import render_template, session, request, jsonify

from models import db
from models.index import Article, User, Classify, Collect, Follow, Like
from . import user_blu


@user_blu.route("/user")
def user():
    user_id = session.get("user_id")
    if user_id:
        user = db.session.query(User).filter(User.id == user_id).first()
        return render_template('index/user.html', user=user)
    else:
        return render_template('index/login.html')


@user_blu.route("/user/follow", methods=["POST"])
def follow():
    a = request.json.get("action")
    writer_id = request.json.get("writer_id")
    user_id = session.get("user_id")
    if not user_id:
        ret = {"err": "101", "errmsg": "请先登录"}
    else:
        if a:
            try:
                follow = Follow(user_id=writer_id, focus_id=user_id)
                db.session.add(follow)
                db.session.commit()
                ret = {"err": "0", "errmsg": "关注成功"}
            except Exception as ret:
                ret = {"err": "102", "errmsg": "关注失败，请稍后重试"}
        else:
            try:
                follow = db.session.query(Follow).filter(Follow.user_id == writer_id,
                                                         Follow.focus_id == user_id).first()
                db.session.delete(follow)
                db.session.commit()
                ret = {"err": "0", "errmsg": "取消关注成功"}
            except Exception as ret:
                db.session.rollback()
                ret = {"err": "103", "errmsg": "取消关注失败,请稍后重试"}
    return jsonify(ret)


@user_blu.route("/user/like", methods=["POST"])
def like():
    art_id = request.json.get("art_id")
    user_id = session.get("user_id")
    if not user_id:
        ret = {"err": "101", "errmsg": "请先登录"}
    else:
        a = db.session.query(Like).filter(Like.article_id == art_id, Like.user_id == user_id).first()
        if a:
            try:
                db.session.delete(a)
                db.session.commit()
                ret = {"err": "0", "errmsg": "取消点赞成功"}
            except Exception as ret:
                db.session.rollback()
                ret = {"err": "101", "errmsg": "取消点赞失败,请稍后重试"}
        else:
            try:
                like = Like(article_id=art_id, user_id=user_id)
                db.session.add(like)
                db.session.commit()
                ret = {"err": "0", "errmsg": "点赞成功"}
            except Exception as ret:
                ret = {"err": "101", "errmsg": "点赞失败，请稍后重试"}
    return jsonify(ret)


@user_blu.route("/user/collect", methods=["POST"])
def collect():
    art_id = request.json.get("art_id")
    user_id = session.get("user_id")
    if not user_id:
        ret = {"err": "101", "errmsg": "请先登录"}
    else:
        a = db.session.query(Collect).filter(Collect.article_id == art_id, Collect.user_id == user_id).first()
        if a:
            try:
                db.session.delete(a)
                db.session.commit()
                ret = {"err": "0", "errmsg": "取消收藏成功"}
            except Exception as ret:
                db.session.rollback()
                ret = {"err": "101", "errmsg": "取消收藏失败,请稍后重试"}
        else:
            try:
                collect = Collect(article_id=art_id, user_id=user_id)
                db.session.add(collect)
                db.session.commit()
                ret = {"err": "0", "errmsg": "收藏成功"}
            except Exception as ret:
                ret = {"err": "101", "errmsg": "点赞失败，请稍后重试"}
    return jsonify(ret)


@user_blu.route("/user/save_detail", methods=['POST'])
def save_detail():
    # 获取用户信息
    avatar_url = request.json.get("avatar_url")
    nick_name = request.json.get("nick_name")
    sign = request.json.get("sign")
    phone = request.json.get("phone")
    sex = request.json.get("sex")
    user_id = session.get("user_id")
    user = db.session.query(User).filter(User.id == user_id).first()
    # 头像
    if avatar_url:
        file_name = str(user_id) + avatar_url[avatar_url.rfind('.'):]
        path = "../../static/upload/" + file_name
        user.avatar_url = path
    if nick_name:
        user.nick_name = nick_name
    if sign:
        user.sign = sign
    if phone:
        user.phone = phone
    if sex:
        user.sex = sex
    try:
        db.session.commit()
        ret = {
            "err": 0,
            "errmsg": "修改成功"
        }
    except Exception as ret:
        ret = {
            "err": '101',
            "errmsg": "修改失败"
        }
    return jsonify(ret)


@user_blu.route("/user/user_write")
def user_write_new():
    user_id = session.get("user_id")
    if user_id:
        user = db.session.query(User).filter(User.id == user_id).first()
        classify = db.session.query(Classify).all()
        return render_template('index/user_write.html', user=user, classify=classify)
    else:
        return render_template('index/login.html')


@user_blu.route("/user/user_write/<int:art_id>")
def user_write_change(art_id):
    user_id = session.get("user_id")
    if user_id:
        user = db.session.query(User).filter(User.id == user_id).first()
        article = db.session.query(Article).filter(Article.id == art_id).first()
        classify = db.session.query(Classify).all()
        return render_template('index/user_write.html', user=user, classify=classify, article=article)
    else:
        return render_template('index/login.html')


@user_blu.route("/user/new_art", methods=['POST'])
def new_art():
    title = request.json.get('title')
    classify = request.json.get('classify')
    content = request.json.get('content')
    user_id = session.get("user_id")
    article = Article()
    article.user_id = user_id
    article.title = title
    article.classify = classify
    article.content = content
    article.status = 1
    article.clicks = 0
    try:
        db.session.add(article)
        db.session.commit()
        ret = {
            "err": 0,
            "errmsg": "发布成功"
        }
    except Exception:
        ret = {
            "err": 101,
            "errmsg": "发布失败，请稍后重试"
        }
    return jsonify(ret)


@user_blu.route("/user/change_art/<int:num>", methods=['POST'])
def change_art(num):
    title = request.json.get('title')
    classify = request.json.get('classify')
    content = request.json.get('content')
    article = db.session.query(Article).filter(Article.id == num).first()
    article.title = title
    article.classify = classify
    article.content = content
    article.status = 1
    try:
        db.session.commit()
        ret = {
            "err": 0,
            "errmsg": "发布成功"
        }
    except Exception:
        ret = {
            "err": 101,
            "errmsg": "发布失败，请稍后重试"
        }
    return jsonify(ret)


@user_blu.route("/user/art_delete/<int:art_id>")
def art_delete(art_id):
    article = db.session.query(Article).filter(Article.id == art_id).first()
    try:
        db.session.delete(article)
        db.session.commit()
        ret = {'err': 0, 'errmsg': '成功'}
    except Exception:
        ret = {'err': 101, 'errmsg': '删除失败，请稍后重试'}
    return jsonify(ret)


@user_blu.route("/user/new_cls", methods=['POST'])
def new_cls():
    cls_name = request.json.get('cls_name')
    cls = Classify()
    cls.name = cls_name
    try:
        db.session.add(cls)
        db.session.commit()
        ret = {
            "err": 0,
            "errmsg": "添加成功"
        }
    except Exception:
        ret = {
            "err": 101,
            "errmsg": "添加失败，请稍后重试"
        }
    return jsonify(ret)


@user_blu.route("/user/change_cls/<int:cls_id>", methods=['POST'])
def change_cls(cls_id):
    cls_name = request.json.get('cls_name')
    cls = db.session.query(Classify).filter(Classify.id == cls_id).first()
    cls.name = cls_name
    cls.update_time = datetime.datetime.now()
    try:
        db.session.commit()
        ret = {
            "err": 0,
            "errmsg": "修改成功"
        }
    except Exception:
        ret = {
            "err": 101,
            "errmsg": "修改失败，请稍后重试"
        }
    return jsonify(ret)


@user_blu.route("/user/cls_delete/<int:cls_id>")
def cls_delete(cls_id):
    classify = db.session.query(Classify).filter(Classify.id == cls_id).first()
    try:
        classify.status = 0
        db.session.commit()
        ret = {'err': 0, 'errmsg': '成功'}
    except Exception:
        ret = {'err': 101, 'errmsg': '删除失败，请稍后重试'}
    return jsonify(ret)
